package org.chy.utils;

import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author Chenghy
 * @date 2018年01月02日 02时14分23秒
 * @version 1.0
 */
@SuppressWarnings("unchecked")
@Component
public class WebUtils {
	
	/**
	 * 按指定的键和值保存到session作用域中
	 * @param name
	 * @param value
	 */
	public static void setSession(String name, Object value) {
		RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
		if (!ObjectUtils.isEmpty(ra)) {
			ra.setAttribute(name, value, RequestAttributes.SCOPE_SESSION);
		}
	}

	/**
	 * 按指定的键获取session作用域中的值
	 * @param name
	 * @return
	 */
	public static <T> T getSession(String name) {
		RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
		if (!ObjectUtils.isEmpty(ra)) {
			return (T) ra.getAttribute(name, RequestAttributes.SCOPE_SESSION);
		}
		return null;
	}

	/**
	 * 按指定的键删除session作用域中的值
	 * @param name
	 */
	public static void removeSession(String name) {
		RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
		if (!ObjectUtils.isEmpty(ra)) {
			ra.removeAttribute(name, RequestAttributes.SCOPE_SESSION);
		}
	}
}
